/*
 * block.c -- this file is part of mISPL.
 * Copyright (C) 2011 Christian Krause
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include "block.h"

block_t block_init(int maxcols, int maxrows) {
	block_t block = malloc(sizeof(__block_s));
	block->maxrows = maxrows;
	block->maxcols = maxcols;
	block->rowcount = 0;
	block->period = -1;
	block->rows = malloc(sizeof(sequence_t) * maxrows);
	block->rowhashs = malloc(sizeof(hashcode_t) * maxrows);
	int i;
	for (i=0; i<maxrows; i++) {
		block->rows[i] = sequence_init(maxcols);
		block->rowhashs[i] = 0;
	}
	return block;
}

void block_clear(block_t block) {
	int i;
	for (i=0; i<block->maxrows; i++) {
		sequence_clear(block->rows[i]);
	}
	free(block->rows);
	free(block->rowhashs);
	free(block);
}

void block_reset(block_t block) {
	block->rowcount = 0;
	block->period = -1;
}

bool_t block_contains_row(block_t block, sequence_t row, hashcode_t hashcode) {
	int i;
	for (i=0; i<block->rowcount; i++) {
		if ((hashcode==block->rowhashs[i]) &&
			sequence_equals(row, block->rows[i])) {
			block->period = i;
			return TRUE;
		}
	}
	return FALSE;
}

bool_t block_add_row(block_t block, sequence_t row, hashcode_t hashcode) {
	// check if the block is full already:
	if (block->rowcount>=block->maxrows) {
		return FALSE;
	}
	block->rowhashs[block->rowcount] = hashcode;
	sequence_copy(block->rows[block->rowcount], row);
	block->rowcount++;
	return TRUE;
}

sequence_t block_get_column(block_t block, int col) {
	if (block->rowcount==0) {
		return NULL;
	}
	sequence_t result = sequence_init(block->rowcount);
	int i;
	for (i=0; i<block->rowcount; i++) {
		mpz_set(result->values[i], block->rows[i]->values[col]);
	}
	result->period = block->period;
	return result;
}
